package A1_回溯;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class LC_40组合总和II {
    LinkedList<Integer> path=new LinkedList<>();
    List<List<Integer>> result=new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        int[] used=new int[candidates.length];
        backtracking(candidates,target,0,0,used);
        return result;
    }
    public void backtracking(int[] nums,int target,int sum,int startIndex,int[] used){
        if(target<sum)
            return;
        if(target==sum){
            result.add(new ArrayList<>(path));
            return;
        }
        for(int i=startIndex;i<nums.length;i++){
            if(i>startIndex && nums[i]==nums[i-1] && used[i-1]==0)
                continue;
            path.add(nums[i]);
            sum+=nums[i];
            used[i]=1;
            backtracking(nums,target,sum,i+1,used);
            path.removeLast();
            sum-=nums[i];
            used[i]=0;
        }
    }
}
